package com.chushula.run;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

public class ProcessExecutor {
	public static void execute(String cmd, String workingDir) {
		try {
			Process p;
			if (workingDir != null)
				p = Runtime.getRuntime().exec(cmd, null, new File(workingDir));
			else
				p = Runtime.getRuntime().exec(cmd);

			BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

			StringBuffer sb = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			System.out.println(sb);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void execute(String cmd) {
		execute(cmd, null);
	}

	public static void execute(CmdEntry cmdEntry) {
		execute(cmdEntry.toCmdString());
	}

	public static class CmdEntry {
		private String cmd;
		private List<String> args = new ArrayList<>();

		public CmdEntry(String cmd) {
			this.cmd = cmd;
		}

		public CmdEntry addArgument(String arg) {
			args.add(arg);
			return this;
		}

		/**
		 * args is seperate by blank
		 * 
		 * @param args
		 * @return
		 */
		public CmdEntry addArguments(String args) {
			List<String> argList = Arrays.asList(args.split("\\s+")).stream().filter(arg -> !StringUtils.isBlank(arg))
					.collect(Collectors.toList());
			argList.forEach(arg -> this.addArgument(args));
			return this;
		}

		public String toCmdString() {
			StringBuffer sBuffer = new StringBuffer();
			sBuffer.append(cmd);
			if (args != null && !args.isEmpty()) {
				sBuffer.append(" ");
				sBuffer.append(String.join(" ", args));
			}
			return sBuffer.toString();
		}
	}

}
